package com.ruoyi.file.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.ocr.v1.OcrClient;
import com.huaweicloud.sdk.ocr.v1.model.*;
import com.ruoyi.file.domain.BusinessLicenseResultVo;
import com.ruoyi.file.domain.IdCardResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;
import java.util.HashMap;

@Repository
@Component
@Slf4j
public class OCRUtil {

    /**
     * @param fileBase64 文件字节流
     * @param colName    文件类型
     * @return ocrResult
     */
    public HashMap<String, Object> getOcr(String fileBase64, String colName, String ak, String sk, String projectId, String endpoint, String accessKeyId, String accessKeySecret, String aliyunocrendpoint) {
        HashMap<String, Object> map = new HashMap<>();

        // 使用默认配置
        HttpConfig config = HttpConfig.getDefaultHttpConfig();
        // 默认连接超时时间为60秒，可根据需要调整
        config.withTimeout(60);
        // 根据需要配置是否跳过SSL证书验证
        // 执行SDK时出现javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure报错，可添加此代码，跳过SSL证书验证
        config.withIgnoreSSLVerification(true);
        // 指定终端节点，以OCR服务北京四的 endpoint 为例
        // 初始化客户端认证信息，需要填写相应 projectId/domainId，以初始化 BasicCredentials 为例
        BasicCredentials basicCredentials = new BasicCredentials()
                .withAk(ak)
                .withSk(sk)
                .withProjectId(projectId);
        // 初始化指定云服务的客户端 {Service}Client ，以初始化 Region 级服务OCR的 OcrClient 为例
        OcrClient client = OcrClient.newBuilder()
                .withHttpConfig(config)
                .withCredential(basicCredentials)
                .withEndpoint(endpoint)
                .build();

        if (colName.contains("businessLicense")) {
            // 营业照识别接口 RecognizeBusinessLicenseRequest
            try {
                RecognizeBusinessLicenseRequest request = new RecognizeBusinessLicenseRequest();
                BusinessLicenseRequestBody body = new BusinessLicenseRequestBody();
                body.withImage(fileBase64);
                request.withBody(body);

                RecognizeBusinessLicenseResponse response = client.recognizeBusinessLicense(request);
                System.out.println(response.toString());

                BusinessLicenseResult result = response.getResult();
                result.setConfidence(null);

                BusinessLicenseResultVo vo = new BusinessLicenseResultVo();
                BeanUtils.copyProperties(result, vo);

                map.put("businessLicense", vo);
            } catch (Exception e) {
                map.put("businessLicense", null);
                e.printStackTrace();
            }
        }
        if (colName.contains("idCard") || colName.toLowerCase().contains("card") || "id_card".equalsIgnoreCase(colName)) {
            // 身份证识别接口 RecognizeIdCardRequest
            RecognizeIdCardRequest request = new RecognizeIdCardRequest();
            IdCardRequestBody body = new IdCardRequestBody();
            body.withImage(fileBase64);
            request.withBody(body);
            try {
                RecognizeIdCardResponse response = client.recognizeIdCard(request);
                System.out.println(response.toString());
                IdCardResult result = response.getResult();

                IdCardResultVo vo = new IdCardResultVo();
                BeanUtils.copyProperties(result, vo);
                map.put("id_card", vo);

            } catch (Exception e) {
                map.put("id_card", null);
                e.printStackTrace();
            }
        }
        if (colName.contains("vehicleLicense")) {
            // 从路径中读取图片并转化成Base64编码字符串
            VehicleLicenseRecognize vehicleLicenseRecognize = new VehicleLicenseRecognize();
            try {
                String result = vehicleLicenseRecognize.getRecognizeVehicleLicenseResult(accessKeyId, accessKeySecret, aliyunocrendpoint, fileBase64);

                JSONObject jsonObj = JSON.parseObject(result);

                System.out.println(jsonObj);
                map.put("vehicleLicense", jsonObj);
            } catch (Exception e) {
                map.put("vehicleLicense", "驾驶证识别不出");
                e.printStackTrace();
            }
        }

        return map;
    }

    public static void main(String[] args) {
        try {
            // 本地图片文件路径
            String filePath = "E:\\绿链恒生\\图片文件\\测试\\202502\\e3d2aba5545d5a708a7342a434cb6c98.jpg";
            File file = new File(filePath);

            // 将图片文件转换为Base64编码字符串
            String fileBase64 = encodeFileToBase64(file);

            // OCR参数配置
            String colName = "idCard"; // 修改为需要识别的证件类型
            String ak = "BUCWPK34O0UFLKADQU4T";
            String sk = "tlLQlEtH8XE8kFDqllcjt04wrTn11VgQtJeTiRVb";
            String projectId = "405c0941c7c14e3db3c2900d20e3df57";
            String endpoint = "https://ocr.cn-north-4.myhuaweicloud.com";
            String accessKeyId = "your-access-key-id";
            String accessKeySecret = "your-access-key-secret";
            String aliyunocrendpoint = "https://ocr.aliyuncs.com";

            OCRUtil ocrUtil = new OCRUtil();
            HashMap<String, Object> result = ocrUtil.getOcr(fileBase64, colName, ak, sk, projectId, endpoint, accessKeyId, accessKeySecret, aliyunocrendpoint);

            System.out.println("OCR识别结果: " + result);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 将文件转换为Base64编码字符串的方法
    private static String encodeFileToBase64(File file) throws IOException {
        byte[] fileBytes = Files.readAllBytes(file.toPath());
        return Base64.getEncoder().encodeToString(fileBytes);
    }
}